package no.ntnu.fp.net.co;

import java.io.EOFException;
import java.io.IOException;

import no.ntnu.fp.net.admin.Log;
import no.ntnu.fp.net.co.Connection;

/**
 * Simplest possible test application, server part.
 * Modified for automated testing purpose
 *
 * @author seb, steinjak
 *
 */
public class TestCoServer {

    /**
     * Empty.
    */
    public TestCoServer() { }

    /**
     * Program Entry Point.
     * @throws  Exception
    */
    public static void main (String args[]) throws Exception {


        // Create log
        Log.setLogName("Server");

        // server connection instance, listen on port 5555
        Connection server = new ConnectionImpl(5555);

        // each new connection lives in its own instance
        Connection conn;

        try {
            conn = server.accept();

            // Check in-order receiving
            int i=0;

            try {
                while (true) {
                    String msg = conn.receive();
                    if(!msg.equals(TestCoClient.data[i])){
                        throw new Exception(msg+" not equal to "+TestCoClient.data[i]);
                    }
                    i++;
                    Log.writeToLog("Message got through to server: " + msg, "TestServer");
                }
            } catch (EOFException e) {
                if (i != TestCoClient.data.length) {
                    throw new Exception("Did not recieve all packets");
                }
                Log.writeToLog("Got close request (EOFException), closing.", "TestServer");
                conn.close();
            }

            System.out.println("*** SERVER TEST FINISHED ***");
            Log.writeToLog("TEST SERVER FINISHED", "TestServer");

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}